﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Dimok.Data;
using Dimok.Data.DataSources;
using Dimok.Web.UI;
using Data.DataSources;

public partial class Controls_Collection_Vantage : TableControl {
	Dimok.User.UserObject uox = new Dimok.User.UserObject();
	public bool IsCollector { get { return uox.IsMemberOf("Collection"); } }
	protected string Filter { get { return Request["Filter"] + ""; } }
	protected string UserName = Dimok.User.UserObject.CurrentUserName;
	protected string UserDomain = Dimok.User.UserObject.CurrentUserDomain;
	protected string UserFullName = Dimok.User.UserObject.CurrentUserPath;
	public string UsixID { get { return GridViewEx.SelectedDataKey == null ? "" : GridViewEx.SelectedDataKey["UsixID"] + ""; } }
	public int CompanyID { get { return GridViewEx.SelectedDataKey == null ? 0 : int.Parse("0"+GridViewEx.SelectedDataKey["CompanyID_Raw"]); } }
	public int LoanID { get { return GridViewEx.SelectedDataKey == null ? 0 : int.Parse("0"+GridViewEx.SelectedDataKey["ApplID"]); } }
	private Profiler profileLib;
	private string[] Groups = new string[]{};
	public bool ShowToday { 
		get { return chkToday.Checked; } set { chkToday.Checked = value; } 
	}
	private string FilterQueue{
		get {
			if (ShowToday) return FILTER_TODAY;
			List<Control> lstBoxes = Dimok.Web.UI.Find.ChildrenByType(phFilters, typeof(CheckBox));
			List<string> filter = new List<string>();
			foreach (CheckBox ch in lstBoxes)
				if (ch.Checked) filter.Add(ch.Attributes["Filter"]);
			return string.Join(" OR ", filter.ToArray());
		}
	}

	#region State
	protected override void SetStateValues(Hashtable values) {
		base.SetStateValues(values);
		Groups = values[ClientID + "Groups"].ToString().Split(',');
		ActiveFilterQueues = values[ClientID + "ActiveFilterQueues"] + "";
		//FilterQueue = values[ClientID + "FilterQueue"] + "";
	}
	protected override void GetStateValues(Hashtable values) {
		base.GetStateValues(values);
		values[ClientID + "Groups"] = string.Join(",", Groups);
		values[ClientID + "ActiveFilterQueues"] = ActiveFilterQueues;
		//values[ClientID + "FilterQueue"] = FilterQueue;
	}
	#endregion

	protected override void OnInit(EventArgs e) {
		base.OnInit(e);
		profileLib = new Profiler(Profile, Page,this);
		RowSelected += new GridViewExEventHandler(USIXExportList_RowSelected);
		ds.Selecting += new ObjectDataSourceSelectingEventHandler(ds_Selecting);
		ds.Selected += new ObjectDataSourceStatusEventHandler(ds_Selected);
		grv.DataBound+=new EventHandler(grv_DataBound);
		ddlFontSize.SelectedIndexChanged += new EventHandler(ddlFontSize_SelectedIndexChanged);
	}
	void ddlFontSize_SelectedIndexChanged(object sender, EventArgs e) {
		profileLib.Page.FontSize = ((ListControl)sender).SelectedValue;
		profileLib.Save();
	}

	void ds_Selecting(object sender, ObjectDataSourceSelectingEventArgs e) {
		ds.Where.Add(FilterQueue);
		if (grv.BuildFilter() == "" && FilterQueue != "" && !ShowToday) {
			string[] locks = Dimok.Locker.LockedList();
			if (locks.Length > 0)
				ds.Where.Add("NOT ApplID IN(" + string.Join(",", locks) + ")");
		} 
		if (grv.SortExpression != "") return;
		SetOrderBys();
		ltrFilter.Text = ds.Wheres().Replace(") AND (", ")<BR>AND (").Replace(" OR ", "<BR>&nbsp OR ");
	}
	bool InReBind = false;
	void ds_Selected(object sender, ObjectDataSourceStatusEventArgs e) {
		System.Data.DataView dv = e.ReturnValue as System.Data.DataView;
		if (dv != null && dv.Count == 1) {
			if (dv[0][0] != DBNull.Value || ShowToday) {
				grv.SelectedIndex = 0;
				return;
			}
			if (InReBind) return;
			if (grv.BuildFilter() != "" && ActiveFilterQueues == "" && SetFilterQueue(false)) {
				ds.Where.Clear();
				ds.Where.Add(grv.BuildFilter());
				RegisterRefresh();
				InReBind = true;
				grv.RequiresDataBinding = true;
				return;
			}
			if (grv.BuildFilter() == "" && ActiveFilterQueues != "") {
				RestoreFilterQueue();
				RegisterRefresh();
			}
		}
	}

	void RegisterRefresh() {
		ScriptManager.RegisterClientScriptBlock(upBridge, this.GetType(), "Refresh", "setTimeout('btnRefresh().click()',100)", true);
	}
	protected override void OnLoad(EventArgs e) {
		base.OnLoad(e);
		GridViewEx = grv;
		ObjectDS = ds;
		if (!IsPostBack && !ScriptManager.GetCurrent(Page).IsInAsyncPostBack) {
			try {
				if (Filter != "") {
					SelectFilter = Filter;
					SetFilterBoxes(Filter);
				} else InitFilter();
				ddlFontSize.SelectedValue = profileLib.Page.FontSize + "";
			} catch { }
		}
		bool check = true;
		if (Filter == "")
			foreach (GridFilterDS.FilterRow row in GetCollectionFilters(Groups)) {
				phFilters.Controls.Add(InitFIlterCheckBox(row.Name, row.Value, check));
		}
	}

	void grv_DataBound(object sender, EventArgs e) {
		if (grv.BuildFilter() == "")
			Dimok.Locker.LockApplicant(LoanID, ConfigLocal.Collection.SessionLengthInMinutes * 60);
		else {
			Dimok.Locker.LockApplicant(0,0);
			Dimok.LocksDS.LocksDataTable dtLock = Dimok.Locker.LockedBy(LoanID);
			if (dtLock.Count > 0) {
				string lockMsg = "alert('User " + dtLock[0].User + " is currently working with this customer.')";
				ScriptManager.RegisterClientScriptBlock(upBridge, this.GetType(), "LockedBY", lockMsg, true);
			}else
				Dimok.Locker.LockApplicant(LoanID, ConfigLocal.Collection.SessionLengthInMinutes * 60);
		}
		//CollectionInfo.UpdateParameters();
	}

	protected void USIXExportList_Command(object sender, CommandEventArgs e) {
		switch (e.CommandName) {
			case "Import":
				Data.SQL.ExecuteSP("usix.s_Export", (e.CommandArgument + "").Split(','));
				break;
			default: throw new NotImplementedException(e.CommandName + " is not implemented");
		}
	}
	protected void USIXExportList_RowSelected(object sender, GridViewExEventArgs e) {
		InitDetails();
	}
	void SetOrderBys() {
		ds.OrderBy.Clear();
		ds.OrderBys = ShowToday ? "NoteStatusDate DESC" : "DateDueBy_Priority DESC,DaysToPTP,DueDateSince DESC,DueAfterHour";
	}
	string FILTER_TODAY { get { return "NoteDate > dbo.Today(GETDATE()) AND [NoteUser] = '" + Dimok.User.UserObject.CurrentUserName + "'"; } }
	const string DEFAULT_FILTER = "1=0";

	GridFilterDS.FilterRow[] GetCollectionFilters(string[] Groups) {
		return (GridFilterDS.FilterRow[])((GridFilterDS.FilterDataTable)dsProfileFilters.SelectEx("Collection","manager_usix_usixbridge_aspx").Table).Select("Name IN ('" + string.Join("','", Groups) + "')");
	}
	void InitFilter() {
		List<string> lstFilter = new List<string>();
		List<string> lstGroups = new List<string>();
		foreach (ADsGroupDS.t_GroupRow drGroup in ADs.LDAP.GetUserGroupsDS(uox.LdapUser).t_Group.Select("dn LIKE '%"+Dimok.Config.ADS.AppGroupsDN+"%'"))
			lstGroups.Add(drGroup.cn);
		Groups = lstGroups.ToArray();
		string[] hideColumns = new string[] { };
		string sortExpression = "";
		foreach (GridFilterDS.FilterRow row in GetCollectionFilters(Groups) ) {
			lstFilter.Add("/*"+row.Name+"*/"+row.Value);
			if (hideColumns.Length < row.HideColumns.Split(',').Length) hideColumns = row.HideColumns.Split(',');
			sortExpression = row.SortExpression;
		}
		//FilterQueue = string.Join(" OR ", lstFilter.ToArray());
		grv.HideColumns = string.Join(",", hideColumns);
		ltrMemberOf.Text = "<div>Member of " + string.Join(",", Groups)+"</div>";
		//if (!IsPostBack)
		//Profile.FilterLast = SelectFilterForProfile;
		//Profile.HideColumnsLast = grv.HideColumns;
		//grv.Caption = SelectFilterForProfile;
	}
	CheckBox InitFIlterCheckBox(string GroupName, string Filter, bool Check) {
		CheckBox ch = new CheckBox();
		ch.Checked = Check;
		ch.Text = "<b>[" + GroupName + "]</b> <FONT color='gray'>" + Filter+"</FONT>";
		ch.Style.Add(HtmlTextWriterStyle.Display, "block");
		ch.CssClass = "CheckBox";
		ch.Attributes.Add("Filter", Filter);
		ch.ID = "chk" + GroupName;
		ch.AutoPostBack = true;
		ch.CheckedChanged += new EventHandler(ch_CheckedChanged);
		return ch;
	}

	void ch_CheckedChanged(object sender, EventArgs e) {
		ShowToday = false;
		//CheckBox chkBox = sender as CheckBox;
		//List<Control> lstBoxes = Dimok.Web.UI.Find.ChildrenByType(phFilters, typeof(CheckBox));
		//foreach (CheckBox ch in lstBoxes)
		//  if (ch != chkBox) ch.Checked = false;
		//List<string> filter = new List<string>();
		//foreach (CheckBox ch in lstBoxes)
		//  if( ch.Checked )filter.Add(ch.Attributes["Filter"]);
		//FilterQueue = string.Join(" OR ", filter.ToArray());
	}
	protected void ClearFilters(object sender, EventArgs e) {
		InitDetails();
		grv.SetFilterBoxes(null);
		ds.Where.Clear();
		grv.RequiresDataBinding = true;
		ShowToday = false;
	}
	string ActiveFilterQueues = "";

	void SaveFilterQueue() {
		List<string> lstFilters = new List<string>();
		List<Control> lstBoxes = Dimok.Web.UI.Find.ChildrenByType(phFilters, typeof(CheckBox));
		foreach (CheckBox ch in lstBoxes)
			if (ch.Checked) lstFilters.Add(ch.ID);
		ActiveFilterQueues = string.Join(",", lstFilters.ToArray());
	}
	void RestoreFilterQueue() {
		List<string> lstFilters = new List<string>(ActiveFilterQueues.Split(','));
		List<Control> lstBoxes = Dimok.Web.UI.Find.ChildrenByType(phFilters, typeof(CheckBox));
		foreach (string id in lstFilters)
			try {
				((CheckBox)Dimok.Web.UI.Find.ControlByID(phFilters, id)).Checked = true;
			} catch { }
		ActiveFilterQueues = "";
	}

	bool SetFilterQueue(bool Checked) {
		SaveFilterQueue();
		bool wasChanged = false;
		List<Control> lstBoxes = Dimok.Web.UI.Find.ChildrenByType(phFilters, typeof(CheckBox));
		foreach (CheckBox ch in lstBoxes) {
			if (ch.Checked != Checked) {
				ch.Checked = Checked;
				wasChanged = true;
			}
		}
		return wasChanged;
	}
	protected void InitDetails() {
		//grvComments.SetFilterBoxes(null);
		grvPayments.SetFilterBoxes(null);
	}
	protected string ShowApplicantJS(object applID) { return "event.cancelBubble = true;if(!event.ctrlKey)showApplInfo(" + applID + ")"; }
}
